import fs from "then-fs"

//读取图书功能
async function getData (){
  let arr = await fs.readFile('./data.json','utf8')
  // console.log(JSON.parse(arr)) 
  return JSON.parse(arr)
}
// console.log(function getData ())
// getData().then(function(e){
//   console.log(e)
// })


//添加图书成功
async function addData (obj){
  try{
    let arr =  await getData()
    obj.id = arr[arr.length-1].id+1
    arr.push(obj)
    fs.writeFile('./data.json',JSON.stringify(arr))
    return '添加成功'
  } catch (e) {
    return '添加失败'
  }
}

// addData({
//   "author": "老子",
//   "bookname": "道德经",
//   "publisher": "老子乐意出版社"
// }).then(function(e){
//   console.log(e)
// })


//删除图书
async function delData(id){
  try{
    let arr =  await getData()
    let newArr = arr.filter( val => val.id != id)
    fs.writeFile('./data.json',JSON.stringify(newArr))
    return '删除成功'
  } catch (e) {
    return '删除失败'
  }
}
// 测试：删除图书
// delData(7).then(e=> console.log(e))


//修改图书
async function updateData(obj){
  try{
    let arr =  await getData()
    let index = arr.indexOf(val => val.id==obj.id)

    arr[index] = obj
    arr.splice(index,1,obj)

    fs.writeFile('./data.json',JSON.stringify(arr))
    return '修改成功'
  } catch (e) {
    return '修改失败'
  }
}
// updateData({
//   "bookname": "狂人日记",
//   "author": "鲁迅",
//   "publisher": "武汉人民出版社",
//   "id": 6
// }).then(e=>console.log(e))


//导出
export default {
  getData,
  addData,
  delData,
  updateData
}